﻿using UnityEngine;
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Security.Cryptography;

#if UNITY_EDITOR
using UnityEditor;
#endif

public class UpdateUtil
{
    /// <summary>计算文件的MD5值</summary>
    public static string Md5file(string file)
    {
        try
        {
            FileStream fs = new FileStream(file, FileMode.Open);
            System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] retVal = md5.ComputeHash(fs);
            fs.Close();

            StringBuilder sb = new StringBuilder();
            int len = retVal.Length;
            for (int i = 0; i < len; i++)
            {
                //sb.Append(retVal[i].ToString("x2"));
                sb.AppendFormat("{0:x2}", retVal[i]);
            }
            return sb.ToString();
        }
        catch (Exception ex)
        {
            throw new Exception("md5file() fail, error:" + ex.Message);
        }
    }

    /// <summary>网络可用</summary>
    public static bool NetAvailable
    {
        get
        {
            return Application.internetReachability != NetworkReachability.NotReachable;
        }
    }

    public static string DataPath
    {
        get
        {
#if UNITY_EDITOR
            return Application.dataPath + "/../HotResource";
#else
            return Application.persistentDataPath;
#endif
        }
    }

    public static string AppContentPath()
    {
        return Application.streamingAssetsPath;
    }

    /// <summary>
    /// 计算文件大小函数(保留两位小数),Size为字节大小
    /// </summary>
    /// <param name="size">初始文件大小</param>
    /// <returns></returns>
    public static string GetFileSize(long size)
    {
        double num = 1024.00; //byte


        if (size < num)
            return size + "B";
        if (size < Math.Pow(num, 2))
            return (size / num).ToString("f2") + "K"; //kb
        if (size < Math.Pow(num, 3))
            return (size / Math.Pow(num, 2)).ToString("f2") + "M"; //M
        if (size < Math.Pow(num, 4))
            return (size / Math.Pow(num, 3)).ToString("f2") + "G"; //G


        return (size / Math.Pow(num, 4)).ToString("f2") + "T"; //T
    }

    /// <summary>获取下载进度字符串</summary>
    /// <param name="curNum"></param>
    /// <param name="totalNum"></param>
    /// <returns></returns>
    public static string GetDownLoadedStr(long curNum,long totalNum)
    {
        return GetFileSize(curNum) + "/" + GetFileSize(totalNum);
    }
}